package org.vectrics.company.web.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;
import org.vectrics.SystemException;
import org.vectrics.common.util.DateSync;
import org.vectrics.common.util.StringUtils;
import org.vectrics.company.Company;
import org.vectrics.company.Sector;
import org.vectrics.company.web.struts.CompanyForm;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.history.HistoryProvider;
import org.vectrics.location.Address;
import org.vectrics.location.Location;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.recruiter.company.RecruitCompanyInfo;
import org.vectrics.recruiter.company.RecruitCompanyService;
import org.vectrics.struts.UserBufferManager;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;


public class SaveCompanyAction extends VectricsStrutsAction {
    private transient final Logger log = Logger.getLogger(SaveCompanyAction.class);
    public static String ID_PARAM = "companyId";
    //private boolean newCompany = false;

    public SaveCompanyAction() {
        super();
    }

    protected void afterPerform(HttpServletRequest request, Company company) {
        //
    }

    protected boolean addressIsBlank(String address1, String address2, String zip, String locationId) {
        boolean result = true;

        if ((address1 != null) && (address1.trim().length() > 0)) {
            result = false;
        }

        if ((address2 != null) && (address2.trim().length() > 0)) {
            result = false;
        }

        if ((zip != null) && (zip.trim().length() > 0)) {
            result = false;
        }

        if ((locationId != null) && (locationId.trim().length() > 0)) {
            result = false;
        }

        return (result);
    }

    public String doExecute(VectricsActionData actionData)
        throws JspException {
        log.debug("doPerform() called");
        String addressEnteredParam = null;
        String address1 = "";
        String address2 = "";
        String zip = "";
        String locationId = "";
        
        boolean newCompany = false;
        CompanyForm form = (CompanyForm)actionData.getForm();
        String companyId = form.getCompanyId();
        if ((companyId == null) || (companyId.equals(""))) {
            log.debug(
                "doPerform() - company not specified in params, assuming we want new company.");
            newCompany = true;
        }
        Company company = null;
        String forward = "success";
        try {
            Person authUser = null;

            try {
                authUser = actionData.getAuthPerson();
            } catch (Exception ex) {
                log.error("Exception getting auth user", ex);
                throw new JspException("Exception getting auth user", ex);
            }

            //String authUserName = authUser.getUser().getUserName();

            ActionErrors errors = new ActionErrors();
            addressEnteredParam = form.getAddress1();
            address1 = form.getAddress1();
            address2 = form.getAddress2();
            zip = form.getPostalCode();
            locationId = form.getLocationId();
            
            if (form.getParentId() != null) {
	            if (form.getParentId().trim().length() <= 0) {
	                form.setParentId(null);
	            }
            }

            if (!actionData.wasButtonPressed("cancel")) {
                if ((form.getName() == null)
                        || (form.getName().trim().length() <= 0)) {
                    errors.add("Company Name",
                        new ActionMessage(actionData.getPhrase("Company Name is required")));
                }

                if (errors.isEmpty()) {
                    log.debug(
                        "doPerform() submit button pressed - saving user..");

                    
                    Long parentId = null;
                    if (form.getParentId() != null)
                        parentId = new Long(form.getParentId());
                    Company parent = null;
                    if (parentId != null) {
                        parent = CoreServiceLocator.getCompanyService().findCompany(parentId);
                    }
                    Sector sector = CoreServiceLocator.getCompanyService().findSector(form.getSectorCode());
                    
                    if (newCompany) {
                		boolean newDomain = false;
                    	if ((form.getCreateDomain() != null) && (form.getCreateDomain().equals("on")))
                    		newDomain = true;
                        log.debug(
                            "doPerform() - company not specified in params, assuming we want new company.");

                        try {
                        	Domain domain = ThreadProperties.getDomain();
                        	if (newDomain) {
                        		Domain parentDomain = null;
                        		if (parent != null) {
                            		parentDomain = parent.getDomain();
                        		} else {
                            		parentDomain = CoreServiceLocator.getConfiguration().getSystemDomain();
                        		}
	                        	company = CoreServiceLocator.getCompanyService().createCompanyAndDomain(StringUtils
	                                    .capitalizeFirstLetter(form.getName()), parent, parentDomain, sector);
                        	} else {
	                        	company =
	                                CoreServiceLocator.getCompanyService().createCompany(domain, StringUtils
	                                    .capitalizeFirstLetter(form.getName()), parent, sector);
                        	}

                            company.setReferenceId(form.getReferenceId());
                            company.setPhone(form.getPhone());
                            company.setPhone2(form.getPhone2());
                            HistoryProvider.getInstance().createHistory(Company.OBJECT_TYPE,
                                company.getId().toString(), "company_create", authUser,
                                "Created a new company with the web interface");
                            form.setCompanyId(company.getId().toString());
                        } catch (Exception de) {
                            log.error("Exception creating new company", de);
                            throw new JspException(de);
                        }
                    } else {
                        log.debug("doPerform() - attempting to find company.");

                        try {
                            company =
                                CoreServiceLocator.getCompanyService().findCompany(new Long(companyId));

                            try {
                                HistoryProvider.getInstance().createHistory(
                                	Company.OBJECT_TYPE,
                                    company.getId().toString(), "company_update", authUser,
                                    "Updated company with the web interface");
                            } catch (Exception ex) {
                                log.error("Exception writing history entry", ex);
                            }
                        } catch (Exception ex) {
                            log.error("getCompanyToEdit() - exception during"
                            		+ " company create", ex);
                        }
                    }
                    
                    if (sector == null)
                    	throw new SystemException("Could not find sector choosen for company: " + form.getSectorCode());
                    company.setSector(sector);

                    company.setName(form.getName());
                    company.setReferenceId(form.getReferenceId());
                    company.setDateLastChange(DateSync.getCurrentTime());
                    company.setParent(parent);
                    company.setPhone(form.getPhone());

                    if (addressIsBlank(address1, address2, zip, locationId)) {
                        log.debug(
                            "doPerform() - home address is blank.  Removing address from company");

                        try {
                            company.setAddress(null);
                            CoreServiceLocator.getCompanyService().updateCompany(company);
                        } catch (Exception de) {
                            log.error("DataException removing address", de);
                            throw new JspException(de);
                        }
                    } else {
                        log.debug("doPerform() - creating address");
                        
                        Address address = company.getAddress();
                        if (address == null) {
                            address = new Address();
                            company.setAddress(address);
                        }
                        address.setAddress1(address1);
                        address.setAddress2(address2);
                        address.setPostalCode(zip);
                        if ((locationId!=null)&&(!locationId.trim().equals(""))) {
							Location location = CoreServiceLocator.getLocationService().findLocation(new Long(locationId));
							address.setLocation(location);
						}
                		CoreServiceLocator.getLocationService().updateAddress(address);

                    }
                    CoreServiceLocator.getCompanyService().updateCompany(company);
                    ThreadProperties.forcedCommit();
                    
                    RecruitCompanyInfo recruitCompanyInfo = RecruitCompanyService.getInstance()
                    		.findRecruitCompanyInfo(company);
                    if (recruitCompanyInfo == null) {
                        recruitCompanyInfo = new RecruitCompanyInfo();
                    }
                    recruitCompanyInfo.setCompany(company);
                    recruitCompanyInfo.setJobPostCompanyInfo(form.getBackground());
                    RecruitCompanyService.getInstance().updateRecruitCompanyInfo(recruitCompanyInfo);
                    ThreadProperties.forcedCommit();
                    
        			UserBufferManager bufMgr = new UserBufferManager();
        			bufMgr.addBufferedObject(actionData.getRequest(), company);
                } else {
                    log.debug("errors found, returning to input page");
                    forward = "invalid";

                    String input = actionData.getMapping().getInput();
                    log.debug("mapping input = " + input);

                    String[] forwards = actionData.getMapping().findForwards();

                    for (int i = 0; i < forwards.length; i++) {
                        String forwardStr = forwards[i];
                        log.debug("mapping forward = " + forwardStr);
                    }
                }
                actionData.getRequest().setAttribute(actionData.getMapping().getAttribute(), form);
                actionData.getRequest().setAttribute("companyId", company.getId().toString());
            } else {
                log.debug("cancel pressed, no action taking");
                forward = "cancel";
                if (newCompany)
                	forward = "cancel.new";
            }
        } catch (Throwable  de) {
            log.error("Exception saving company information", de);
            throw new JspException("Exception saving company information", de);
        } 
        ThreadProperties.forcedCommit();
        if (companyId != null) {
        	actionData.getRequest().addParameter("companyId", companyId);
        }
        return (forward);
    }
    
}
